package com.haotian.zip.web;

import java.io.IOException;
import java.util.zip.GZIPInputStream;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;

/**
 * 
 * @ClassName: GzipRequestWrapper
 * @Description: TODO
 * @author: mr.zhurunhua
 * @date: 2017年6月16日 下午4:24:29
 */
final class GzipRequestWrapper extends HttpServletRequestWrapper {
	public static final Logger LOGGER = Logger.getLogger(GzipRequestWrapper.class);
	private HttpServletRequest request;

	public GzipRequestWrapper(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		ServletInputStream stream = request.getInputStream();
		String contentEncoding = request.getHeader("Content-Encoding");
		// 如果对内容进行了压缩，则解压
		if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
			try {
				final GZIPInputStream gzipInputStream = new GZIPInputStream(stream);
				ServletInputStream newStream = new ServletInputStream() {
					@Override
					public int read() throws IOException {
						return gzipInputStream.read();
					}

					@Override
					public boolean isFinished() {
						// TODO 自动生成的方法存根
						return false;
					}

					@Override
					public boolean isReady() {
						// TODO 自动生成的方法存根
						return false;
					}

					@Override
					public void setReadListener(ReadListener readListener) {
						// TODO 自动生成的方法存根
					}
				};
				return newStream;
			} catch (Exception e) {
				LOGGER.error("ungzip content fail.", e);
			}
		}
		return stream;
	}
}